import { getCurrentInstance, onUnmounted, watch, toRaw, reactive, nextTick, shallowRef, onMounted } from 'vue'
import { useStore } from 'vuex'
import { isEqual } from '@/utils'

/**
 * @desc 从字符中提取出绘制类型[darkMode]
 * @returns String  | undefined
 * **/
function exactKey(str) {
  const matchResult = str.match(/-(\S*)/)
  return matchResult ? matchResult[1] : void 0
}

/**
 * @desc    操作地图hook
 * @author  邓清波
 * @date    2022/1116
 * @param   hookOptions  {Object}
 * @param   hookOptions.isRemovePrev Boolean {default:false} {每一次调用前是否删除上一次方法创建的点}
 */
function useMapOperates(hookOptions = { isRemovePrev: false }) {
  const store = useStore()
  const { proxy } = getCurrentInstance()

  // 如有其他的点位类型在加
  const modeMethodsName = {
    // 点
    marker: {
      createMethodName: 'createMvMapMarkerLayer',
      removeMethodName: 'removeMvMapMarkerLayer'
    },
    // 海量点
    point: {
      createMethodName: 'createMvMapMassPoint',
      removeMethodName: 'setMvMapMassPoint'
    },
    // 路线
    polyline: {
      createMethodName: 'createMvMapLineLayer',
      removeMethodName: 'removeMvMapLineLayer'
    },
    // 图片
    image: {
      createMethodName: 'createMvMapImgLayer',
      removeMethodName: 'removeMvMapImgLayer'
    },
    // 附近摄像机
    aroundCamera: {
      createMethodName: 'showCameraPoint',
      removeMethodName: 'cameraClose'
    }
  }

  const currentComponentName = proxy.$options.name
  let mapModeInstance = {} // 点位/路线 实例

  /**
   * 移除所有点位路线
   */
  function removeAll() {
    // console.log('remove run')
    const mapSdk = proxy.$mapSdk()
    mapSdk && mapSdk.hidePopup()
    try {
      for (const i in mapModeInstance) {
        const removeName = modeMethodsName[exactKey(i)].removeMethodName

        mapModeInstance[i] && (mapModeInstance[i] = mapSdk[removeName](mapModeInstance[i]))
      }
      // console.log('mapModeInstance', mapModeInstance)
    } catch (e) {
      // console.warn('removeAll catch', e)
    } finally {
      mapModeInstance = {}
      mapSdk && mapSdk.setMvMapClickMarker && mapSdk.setMvMapClickMarker()
    }
  }

  onUnmounted(() => {
    stop()
    removeAll()
  })

  const stop = watch(
    () => store.state.config.detailConfig,
    (newV, pervV) => {
      const _new = { ...newV, data: toRaw(newV.data), config: toRaw(newV.config) }
      const _prev = { ...pervV, data: toRaw(pervV.data), config: toRaw(pervV.config) }

      if (!isEqual(_new, _prev)) {
        removeAll()
      }
    },
    {
      deep: true
    }
  )

  return function (darkMode, dataSource, darkOptions = {}) {
    if (!(darkMode in modeMethodsName)) {
      return console.error(`error darkMode 【 ${darkMode} 】`)
    }
    if (!dataSource) return

    hookOptions.isRemovePrev && removeAll()

    const { createMethodName } = modeMethodsName[darkMode] // 绘制方法名;

    function callback(e, darkDetail) {
      if (e.type == 'click') {
        proxy.$mapSdk().pointClick(e, darkDetail, {
          componentName: currentComponentName,
          mode: darkMode,
          type: darkOptions.type
        })
      }
    }
    let args = [dataSource, darkOptions, callback]

    // polyline 第二个参数是回调,与其他mode参数位置不一致
    if (darkMode === 'polyline') {
      //  args = [dataSource, callback]; // 路线先不给点击事件
      args = [dataSource]
    } else if (darkMode === 'image') {
      args = [dataSource, darkOptions]
    }
    const randomKey = `${Math.random().toString()}-${darkMode}`
    mapModeInstance[randomKey] = proxy.$mapSdk()[createMethodName](...args)
  }
}

export default useMapOperates
